/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* aTemp = headA;
        ListNode* bTemp = headB;
        while(aTemp != nullptr && bTemp != nullptr){
            aTemp = aTemp->next;
            bTemp = bTemp->next;
        }

        if(aTemp == nullptr && bTemp == nullptr){ // AB一样长
            aTemp = headA;
            bTemp = headB;
        } else if(aTemp == nullptr) { // B长
            aTemp = headB;
            while(bTemp != nullptr){
                aTemp = aTemp->next;
                bTemp = bTemp->next;
            }
            bTemp = aTemp;
            aTemp = headA;
        } else {    // A长
            bTemp = headA;
            while(aTemp != nullptr){
                aTemp = aTemp->next;
                bTemp = bTemp->next;
            }
            aTemp = bTemp;
            bTemp = headB;
        }

        while(aTemp != nullptr && bTemp != nullptr){
            if(aTemp == bTemp){
                return aTemp;
            } else {
                aTemp = aTemp->next;
                bTemp = bTemp->next;
            }
        }

        return nullptr;
    }
};